<?php


namespace App\Http\Controllers;


use App\Models\Form;
use App\Models\Page;
use App\Utils\Parser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PublishController extends Controller
{

    public function publish(Request $request){
        $this->validate($request, [
            'sq_id' => 'nullable|string',
            'data'  => 'required|array',
            'page'  => 'array'
        ]);
        $sqId = $request->get('sq_id', '');
        $page = null;
        if($sqId){
            $page = Page::whereSqId($sqId)->first();
        }
        if(!$page){
            list($usec, $sec) = explode(" ", microtime());
            $sqId = md5($sec.' '.$usec);
            $page = new Page();
            $page->user_id = $this->loginUser ? $this->loginUser->id : 0;
            $page->sq_id = $sqId;
        }
        $data = $request->get('data');
        $pageData = $request->get('page');
        $page->elements = [
            'data' => $data,
            'page' => $pageData,
        ];
        $page->save();
        $forms = Parser::formParser($data, $this->loginUserId, $page->sq_id);
        foreach ($forms as $form){
            $dbForm = Form::whereFormId($form['form_id'])->first();
            if($dbForm){
                $dbForm->update($form);
            }else{
                Form::create($form);
            }
        }
        Cache::forever('pub:'.$sqId, $page->elements);
        return self::success([
            'url'   => url('/page/'.$sqId.'?async=true'),
            'sq_id' => $sqId,
        ]);
    }

}
